package com.by.tools;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/9 14:18
 * @注释
 */
import com.by.annotion.Column;
import com.by.annotion.Entity;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleORM {

    private Connection connection;

    public SimpleORM(String url, String username, String password) throws SQLException {
        this.connection = DriverManager.getConnection(url, username, password);
    }

    // 插入数据
    public <T> void insert(T entity) throws Exception {
        Class<?> clazz = entity.getClass();
        Entity entityAnnotation = clazz.getAnnotation(Entity.class);
        if (entityAnnotation == null) {
            throw new IllegalArgumentException("Entity annotation not found on class " + clazz.getName());
        }

        StringBuilder columns = new StringBuilder();
        StringBuilder placeholders = new StringBuilder();
        List<Object> values = new ArrayList<>();

        for (Field field : clazz.getDeclaredFields()) {
            Column columnAnnotation = field.getAnnotation(Column.class);
            if (columnAnnotation != null) {
                field.setAccessible(true);
                columns.append(columnAnnotation.name()).append(", ");
                placeholders.append("?, ");
                values.add(field.get(entity));
            }
        }

        String tableName = entityAnnotation.tableName();
        String sql = "INSERT INTO " + tableName + " (" +
                columns.substring(0, columns.length() - 2) + ") VALUES (" +
                placeholders.substring(0, placeholders.length() - 2) + ")";

        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            for (int i = 0; i < values.size(); i++) {
                statement.setObject(i + 1, values.get(i));
            }
            statement.executeUpdate();
        }
    }

    // 查询数据
    public <T> List<T> queryAll(Class<T> clazz) throws Exception {
        Entity entityAnnotation = clazz.getAnnotation(Entity.class);
        if (entityAnnotation == null) {
            throw new IllegalArgumentException("Entity annotation not found on class " + clazz.getName());
        }

        String tableName = entityAnnotation.tableName();
        String sql = "SELECT * FROM " + tableName;

        List<T> results = new ArrayList<>();
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {

            while (resultSet.next()) {
                T instance = clazz.getDeclaredConstructor().newInstance();
                for (Field field : clazz.getDeclaredFields()) {
                    Column columnAnnotation = field.getAnnotation(Column.class);
                    if (columnAnnotation != null) {
                        field.setAccessible(true);
                        field.set(instance, resultSet.getObject(columnAnnotation.name()));
                    }
                }
                results.add(instance);
            }
        }
        return results;
    }

    // 关闭连接
    public void close() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    }
}
